<template>
  <el-table :data="tableData" :row-style="{ height: '77px' }" border
            style="width: calc(100vw - 240px);height: 75vh;margin-top: 20px;font-size: 15px;">
    <el-table-column align="center" prop="topName" label="配置名称" width="auto"/>
    <el-table-column prop="url" label="配置图片" align="center">
      <template v-slot="scope">
        <div @click="openPreview(scope.row.url)" style="cursor: pointer;">
          <el-image style="width: 100px; height: 100px" :src="scope.row.url"></el-image>
        </div>
      </template>
    </el-table-column>
    <el-table-column align="center" fixed="right" label="操作" width="200">
      <template v-slot="scope">
        <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!--      分页-->
  <div style="margin-top: 10px">
    <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :background="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
    />
  </div>

  <!-- 添加/编辑对话框 -->
  <el-dialog :close-on-click-modal="false" title="配置操作" v-model="dialogVisible" width="560" @close="reset('form')">
    <el-form label-position="left" :inline="true" :model="form" ref="form" :rules="rules">
      <el-form-item label="配置名称" style="width: 90%" prop="topName">
        <el-input v-model="form.topName" placeholder="请输入配置名称" clearable/>
      </el-form-item>
    </el-form>
    <el-form-item label="配置图标" prop="url">
      <el-upload
              class="avatar-uploader"
              :before-upload="checkFileType"
              :action="'/api/files/upload'"
              :on-success="photoHandleSuccess"
              :on-error="photoHandleError"
              :show-file-list="false"
      >
        <img width="100" height="100" v-if="form.url" :src="form.url" class="avatar">
        <el-icon v-else class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
      </el-upload>
    </el-form-item>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="reset('form')">取消</el-button>
        <el-button type="primary" @click="submitForm('form')">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <ImagePreview ref="preview" :imageUrl="currentPreviewImage" />
</template>

<script>
  import {ref} from 'vue'
  import request from "~/utils/request.js";
  import ImagePreview from '~/pages/ImagePreview.vue';

  export default {
    components: {
      ImagePreview
    },
    data() {
      return {
        dialogVisible: false,
        tableData: [],
        form: {},
        search: '',
        currentPage: 1,
        pageSize: 10,
        total: 0,
        currentPreviewImage: '', // 当前预览的图片URL
        rules: {
          topName: [
            {required: true, message: '请输入配置名称', trigger: 'blur'},
          ],
          url: [
            {required: true, message: '请上传配置图片', trigger: 'blur' },
          ]
        }
      }
    },
    created() {
      this.load()
    },
    methods: {
      load() {
        request.get("/config/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&name=" + this.search).then(res => {
          if (res.code === '200') {
            this.tableData = res.data.records
            this.total = res.data.total
          } else {
            ElMessage.error("错误" + res.msg)
          }
        })
      },
      editItem(item) {
        Object.assign(this.form, item)
        this.dialogVisible = true
      },
      // 提交
      submitForm(val) {
        this.$refs[val].validate((valid) => {
          if (valid) {
            request.post("/config/edit", this.form).then(res => {
              if (res.code === '200') {
                this.$message({
                  message: "成功",
                  type: "success"
                })
                this.load()
                this.reset(val)
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        })
      },
      // 取消
      reset(val) {
        this.dialogVisible = false;
        this.form = {};
        this.$refs[val].resetFields();
      },
      handleCurrentChange(item) {
        // 改变当前页码触发
        this.currentPage = item
        this.load()
      },
      handleSizeChange(item) {   // 改变当前每页的个数触发
        this.pageSize = item
        this.load()
      },
      photoHandleSuccess(response) {
        this.form.url = `/api/file/download/${response}`
        this.$message.success('上传成功');
      },
      photoHandleError() {
        this.$message.error("上传文件失败")
      },
      checkFileType(file) {
        const maxSize = 1024 * 1024 * 1024;
        if (file.size > maxSize) {
          this.$message.warning('文件大小超过1GB限制!');
          return false;
        }
        return true;
      },
      openPreview(imageUrl) {
        if (!imageUrl) return;
        this.currentPreviewImage = imageUrl;
        this.$nextTick(() => {
          this.$refs.preview.open();
        });
      }
    }
  }
</script>

<style scoped>
</style>
